<template>
  <a-modal
    :title="titles==='edit' ? '编辑邮件模板': '新建邮件模板'"
    :width="800"
    :visible="modalVisibal"
    @cancel="handleCancel"
    :destroyOnClose="true"
    :keyboard="false"
    :maskClosable="false"
    :closable="true"
    :centered="true"
    :z-index="99"
  >
    <div class="mailTemplateManagement">
      <a-form-model
        layout="vertical"
        ref="formComp"
        :model="formData"
        :rules="rules">
        <a-row :gutter="[16, 0]">
          <a-col :span="12">
            <a-form-model-item label="邮件模板名称：" prop="name">
              <a-input
                :placeholder="$t('pleaseInput') + '邮件模板名称'"
                :maxLength="100"
                v-model="formData.name"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="归属业务类型：" prop="businessType">
              <a-select
                v-model="formData.businessType"
                :allowClear="true"
                :filterOption="$commonFun.filterOption"
                :placeholder="$t('pleaseSelect') + '归属业务类型'"
                showSearch>
                <a-select-option v-for="item in businessAttributionType" :key="item.name" :value="item.name">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="[16, 0]">
          <a-col :span="24">
            <a-form-model-item label="邮件主题：" prop="title">
              <a-input
                :placeholder="$t('pleaseInput') + '邮件主题... (邮件主题只能为无格式的普通文本)'"
                :maxLength="50"
                v-model="formData.title"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class="carModelDetailMainBottom">
          <a-tabs class="tabCommon" @change="changeTab" :default-active-key=" titles==='new' ? 1 : formData.isHtml">
            <a-tab-pane :key="1" tab="富文本编辑">
              <editor id="tinymce" v-model="formData.richTextValue" :init="init" ></editor>
            </a-tab-pane>
            <a-tab-pane :key="0" tab="普通文本编辑">
              <a-form-model-item prop="normalTextValue">
                <a-textarea
                  style="width: 100%;height: 300px"
                  v-model="formData.normalTextValue"
                  placeholder="请输入文字，只能输入普通文本，不含非法的特殊字符"></a-textarea>
              </a-form-model-item>
            </a-tab-pane>
          </a-tabs>
        </div>
        <h5>备注说明：“${}以及括起来的部分”为动态数据，不可进行编辑操作；</h5>
        <h5>请勿编辑修改动态变化内容，否则可能引发邮件推送错误；</h5>
        <h5>仅限修改静态内容；</h5>
      </a-form-model>
    </div>
    <div slot="footer">
      <div>
        <a-button @click="handleCancel" type="primary" :ghost="true">{{ $t('cancel') }}</a-button>
        <a-button @click="handleSave" type="primary">保存并关闭</a-button>
      </div>
    </div>
  </a-modal>
</template>
<script>
import tinymce from 'tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver/theme'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/wordcount'
import 'tinymce/icons/default/icons'
import placeholder from '@comp/RichTextEditor/placeholder'

export default {
  components: { Editor },
  props: {
    titles: {
      type: String,
      default: '标题'
    },
    emailTemplateInfo: {
      type: Object,
      default: () => {}
    }
  },
  created () {
    placeholder(tinymce)
    this.getBusinessAscriptionType()
  },
  computed: {
    watchobj () {
      const { titles, emailTemplateInfo, count } = this
      return {
        titles,
        emailTemplateInfo,
        count
      }
    }
  },
  data () {
    return {
      formData: {
        richTextValue: '',
        normalTextValue: '',
        name: '',
        businessType: undefined,
        isHtml: 1,
        message: '',
        title: '',
        id: ''
      },
      modalVisibal: false,
      init: {
        language_url: './zh_CN.js', // 语言包位置，因为放在public下所以可以省略public
        selector: '#tinymce', //tinymce的id
        language: 'zh_CN', //语言类型
        skin_url: './skins/ui/oxide',
        placeholder: '请输入邮件模板内容, 可根据需求调整内容格式 ...',
        height: 340, //编辑器高度
        width: 744,
        forced_root_block: '',
        browser_spellcheck: true, // 拼写检查
        // elementpath: false, //禁用编辑器底部的状态栏
        // statusbar: false, // 隐藏编辑器底部的状态栏
        paste_data_images: true, // 允许粘贴图像
        // menubar: false, //最顶部文字信息
        plugins: 'image link code table lists wordcount placeholder',
        branding: false, //是否禁用“Powered by TinyMCE”
        toolbar: 'fontselect fontsizeselect link lineheight forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | image quicklink h2 h3 blockquote table numlist bullist preview fullscreen', //工具栏
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;'
      },
      rules: {
        name: [{ required: true, message: this.$t('pleaseInput') }],
        businessType: [{ required: true, message: this.$t('pleaseSelect') }],
        title: [{ required: true, message: this.$t('pleaseInput') }],
        normalTextValue: [{ required: true, message: this.$t('pleaseInput') }]
      },
      businessAttributionType: [],
      count: 0
    }
  },
  watch: {
    'formData.normalTextValue' (newValue, oldValue) {
      this.formData.normalTextValue = this.getContent(newValue)
      this.formData.message = this.formData.normalTextValue
    },
    'formData.richTextValue' (newValue, oldValue) {
      this.formData.message = newValue
      console.log(newValue,'formData.richTextValue')
    },
    watchobj: {
      immediate: true,
      handler (newValue, oldValue) {
        this.getBusinessAscriptionType()
        console.log(newValue, oldValue,'newValue, oldValue')
        if (newValue.titles === 'edit') {
          console.log(this.emailTemplateInfo.id, 'this.emailTemplateInfo.id')
          this.formData.businessType = this.emailTemplateInfo.businessType
          this.formData.isHtml = this.emailTemplateInfo.isHtml ? 1 : 0
          // this.formData.message = this.emailTemplateInfo.message
          this.formData.name = this.emailTemplateInfo.name
          this.formData.title = this.emailTemplateInfo.title
          this.formData.id = this.emailTemplateInfo.id
          this.formData.richTextValue = this.emailTemplateInfo.message
          this.formData.normalTextValue = this.getContent(this.emailTemplateInfo.message)
          // }
        } else if (newValue.titles === 'new') {
          this.formData.businessType = undefined
          this.formData.isHtml = 1
          this.formData.message = ''
          this.formData.name = ''
          this.formData.title = ''
          this.formData.id = ''
          this.formData.richTextValue = ''
          this.formData.normalTextValue = ''
        }
      }
    },
    'formData.isHtml' (newValue, oldValue) {
      if (newValue === 1) {
        this.formData.message = this.formData.richTextValue
      } else if (newValue === 0) {
        this.formData.message = this.formData.normalTextValue
      }
    }
  },
  mounted () {
    tinymce.init({ })
  },
  methods: {
    getContent (html) {
      let text = html;
      // 替换掉&nbsp;
      text = text.replace(/&nbsp;/g, ' ');
      // 替换掉HTML标签,删除行内样式，删除空格
      text = text.replace(/<style([\s\S]*?)<\/style>/gi, '');
      text = text.replace(/<script([\s\S]*?)<\/script>/gi, '');
      text = text.replace(/<(\w+)[^>]*>/gi, '<$1>');
      text = text.replace(/<[^>]+>/g, '');
      text = text.replace(/^\s+|\s+$/g, '');
      text = text.replace(/\s/g, '');
      text = text.replace(/[\r\n]/g, '');
      console.log(text, '转化为普通文本')
      return text;
    },
    shutDown () {
      this.modalVisibal = !this.modalVisibal
    },
    changeTab (val) {
      this.formData.isHtml = val
      this.$warning({
        title: '确认进行 富文本编辑/普通文本编辑 切换？',
        content: '切换后原编辑方式输入的模板内容将失效，以最新编辑输入的模板内容为准',
        okText: '我知道了',
        onOk () {
        }
      })
    },
    // 取消
    handleCancel () {
      this.shutDown()
      this.handleCount()
      this.$emit('againValue')
    },
    handleCount () {
      this.count += 1
    },
    // 保存
    handleSave () {
      const addParameters = {
        businessType: this.formData.businessType,
        isHtml: this.formData.isHtml,
        message: this.formData.message,
        name: this.formData.name,
        title: this.formData.title
      }
      const editParameters = {
        businessType: this.formData.businessType,
        isHtml: this.formData.isHtml,
        message: this.formData.message,
        name: this.formData.name,
        id: this.formData.id,
        title: this.formData.title
      }
      this.$refs.formComp.validate((valid) => {
        console.log(valid,'valid')
        if (this.formData.name && this.formData.businessType && this.formData.title) {
          if ((this.formData.richTextValue && this.formData.isHtml === 1) || (this.formData.normalTextValue && this.formData.isHtml === 0)) {
            this.$refs.formComp.clearValidate('normalTextValue')
            if (this.titles === 'new') {
              this.$api.addEmailMessageTemplate(addParameters).then(() => {
                this.shutDown()
                this.$message.success(this.$t('successfullyOperation'))
                this.$emit('flushed')
                this.handleCount()
              })
            } else {
              this.$api.editEmailMessageTemplate(editParameters).then(() => {
                this.shutDown()
                this.$message.success(this.$t('successfullyOperation'))
                this.$emit('flushed', this.formData.id)
              })
            }
          } else if (!this.formData.richTextValue && this.formData.isHtml === 1) {
            console.log('aaaaaaaaaaaaaaa')
            this.$refs.formComp.clearValidate('normalTextValue')
            this.$message.error('富文本编辑框或普通文本编辑框不能为空')
          } else if (!this.formData.normalTextValue && this.formData.isHtml === 0) {
            console.log('oooooooooooooooooooooo')
            this.$message.error('富文本编辑框或普通文本编辑框不能为空')
          }
        } else if (!this.formData.richTextValue && this.formData.isHtml === 1) {
          console.log('bbbbbbbbbbbbb')
          this.$message.error('富文本编辑框或普通文本编辑框不能为空')
          this.$refs.formComp.clearValidate('normalTextValue')
        } else if (!this.formData.normalTextValue && this.formData.isHtml === 0) {
          console.log('cccccccccccc')
          this.$message.error('富文本编辑框或普通文本编辑框不能为空')
        }
      })
    },
    // 获取业务归属类型
    getBusinessAscriptionType () {
      this.$api.getBusinessTypeList().then((res) => {
        this.businessAttributionType = res.data
        this.businessAttributionType.push({
          value: '无业务关联-暂存',
          name: '无业务关联-暂存',
          remarks: '',
          id: '' })
      })
    }
  }
}
</script>
<style scoped lang="less">
  .mailTemplateManagement {
    overflow-x: hidden;
    overflow-y: auto;
    height: 610px;
    .carModelDetailMainBottom {
      height: 400px;
  flex: 1 0 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  > .ant-tabs {
    flex: 1 0 0;
    display: flex;
    flex-direction: column;
    .ant-tabs-content {
      flex: 1 0 0;
    }
  }
   .tabCommon {
    .ant-tabs-bar {
      .ant-tabs-nav {
        .ant-tabs-tab {
          padding: 0 0 6px 0;
        }
      }
    }
  }
  .tablePageWarp {
    padding:0;
  }
}
  }
  /deep/.ant-form-item {
    margin-bottom: 0;
  }
</style>
